package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {

    @Autowired
    private WorkerCertificationAuditMapper workerCertificationAuditMapper;

    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commit(WorkerCertificationAuditAddReqDTO auditAddReqDTO) {
        // 1.更新信息到服务人员认证信息表
        WorkerCertification entity = BeanUtil.toBean(auditAddReqDTO, WorkerCertification.class);
        entity.setId(auditAddReqDTO.getServeProviderId());
        entity.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        WorkerCertification one = lambdaQuery().eq(WorkerCertification::getId, auditAddReqDTO.getServeProviderId())
                .one();
        if (ObjectUtil.isNull(one)) {
            super.save(entity);
        } else {
            super.updateById(entity);
        }

        // 2.更新信息到服务人员认证审核表
        WorkerCertificationAudit audit = BeanUtil.toBean(auditAddReqDTO, WorkerCertificationAudit.class);
        audit.setId(null);
        audit.setServeProviderId(entity.getId());
        audit.setCreateTime(LocalDateTime.now());
        audit.setUpdateTime(LocalDateTime.now());
        workerCertificationAuditMapper.insert(audit);
    }

    @Override
    public RejectReasonResDTO rejectReason(Long userId) {
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper
                .selectOne(Wrappers.<WorkerCertificationAudit>lambdaQuery()
                        .eq(WorkerCertificationAudit::getServeProviderId, userId)
                        .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                        .orderByDesc(WorkerCertificationAudit::getUpdateTime)
                );
        return ObjectUtil.isNull(workerCertificationAudit) ? null : new RejectReasonResDTO(workerCertificationAudit.getRejectReason());
    }

    @Override
    public PageResult<WorkerCertificationAuditResDTO> getPage(WorkerCertificationAuditPageQueryReqDTO reqDTO) {
        Integer auditStatus = reqDTO.getAuditStatus();
        Integer certificationStatus = reqDTO.getCertificationStatus();
        String idCardNo = reqDTO.getIdCardNo();
        String name = reqDTO.getName();
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(reqDTO, WorkerCertificationAudit.class);
        Page<WorkerCertificationAudit> auditPage = workerCertificationAuditMapper.selectPage(page,
                Wrappers.<WorkerCertificationAudit>lambdaQuery()
                        .eq(auditStatus != null, WorkerCertificationAudit::getAuditStatus, auditStatus)
                        .eq(certificationStatus != null, WorkerCertificationAudit::getCertificationStatus, certificationStatus)
                        .eq(StringUtils.isNoneBlank(idCardNo), WorkerCertificationAudit::getIdCardNo, idCardNo)
                        .like(StringUtils.isNoneBlank(name), WorkerCertificationAudit::getName, ("%" +name + "%"))
        );
        return PageUtils.toPage(auditPage, WorkerCertificationAuditResDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, Integer certificationStatus, String rejectReason, Long userId, String name) {
        // 根据认证状态判断是通过还是驳回
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper.selectById(id);
        if (ObjectUtil.isNull(workerCertificationAudit)) {
            throw new BadRequestException("认证信息不存在");
        }
        workerCertificationAudit.setAuditStatus(AuditStatusEnum.YES.getStatus());
        workerCertificationAudit.setAuditorId(userId);
        workerCertificationAudit.setAuditorName(name);
        workerCertificationAudit.setAuditTime(LocalDateTime.now());
        if (certificationStatus == CertificationStatusEnum.SUCCESS.getStatus()) {
            // 认证成功
            // 更新服务人员认证审核表
            workerCertificationAudit.setCertificationStatus(CertificationStatusEnum.SUCCESS.getStatus());
            workerCertificationAuditMapper.updateById(workerCertificationAudit);
        }else if (certificationStatus == CertificationStatusEnum.FAIL.getStatus()) {
            // 失败
            // 更新服务人员认证审核表
            workerCertificationAudit.setCertificationStatus(CertificationStatusEnum.FAIL.getStatus());
            workerCertificationAudit.setRejectReason(rejectReason);
            workerCertificationAuditMapper.updateById(workerCertificationAudit);
        } else {
            throw new BadRequestException("认证状态异常");
        }
        // 更新服务人员认证信息表
        WorkerCertification entity = BeanUtil.toBean(workerCertificationAudit, WorkerCertification.class);
        entity.setId(workerCertificationAudit.getServeProviderId());
        entity.setCertificationTime(LocalDateTime.now());
        boolean ret = super.updateById(entity);
        if (!ret) {
            throw new BadRequestException("更新人员信息认证异常");
        }
    }
}
